import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:state_manage/infinite_list/bloc/bloc.dart';
import 'package:http/http.dart' as http;
import 'package:state_manage/infinite_list/post.dart';

/// 永动列表
class InfiniteListTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Infinite Scroll',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Posts'),
        ),
        body: BlocProvider<InfiniteBloc>(
          create: (ctx) =>
              InfiniteBloc(httpClient: http.Client())..add(Fetch()),
          child: HomePage(),
        ),
      ),
    );
  }
}

//// 主页
class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

/// 页面状态
class _HomePageState extends State<HomePage> {
  // 滚动控制器
  final _scrollController = ScrollController();
  // 滚动域
  final _scrollThreshold = 200.0;
  // 文章Bloc
  InfiniteBloc _bloc;

  /// 初始化
  @override
  void initState() {
    super.initState();
    // 添加监听
    _scrollController.addListener(_onScroll);
    // 获取Bloc
    _bloc = BlocProvider.of(context);
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<InfiniteBloc, InfiniteState>(
      builder: (ctx, state) {
        // 第一批数据加载
        if (state is PostUninitialized) {
          return Center(
            child: CircularProgressIndicator(),
          );
        } else if (state is PostError) {
          return Center(
            child: Text('failed to fetch posts.'),
          );
        } else if (state is PostLoaded) {
          // 文件为空
          if (state.posts.isEmpty) {
            return Center(
              child: Text('no posts.'),
            );
          }
          return ListView.builder(
            itemBuilder: (ctx, index) {
              return index >= state.posts.length
                  ? BottomLoader()
                  : InfiniteListItem(post: state.posts[index]);
            },
            itemCount: state.hasReachedMax
                ? state.posts.length
                : state.posts.length + 1,
            controller: _scrollController,
          );
        }
      },
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  /// 滚动监听
  void _onScroll() {
    // 最大滚动位置
    final maxScroll = _scrollController.position.maxScrollExtent;
    // 获取当前位置
    final currentScroll = _scrollController.position.pixels;
    // 判断是否加载数据
    if (maxScroll - currentScroll <= _scrollThreshold) {
      _bloc.add(Fetch());
    }
  }
}

/// 底部加载控件
class BottomLoader extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Center(
        child: SizedBox(
          width: 33,
          height: 33,
          child: CircularProgressIndicator(
            strokeWidth: 1.5,
          ),
        ),
      ),
    );
  }
}

/// 列表组件
class InfiniteListItem extends StatelessWidget{
  /// 文章
  final Post post;

  const InfiniteListItem({Key key, @required this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {    
    return ListTile(
      leading: Text(
        '${post.id}',
        style: TextStyle(fontSize: 10.0),
      ),
      title: Text(post.title),
      isThreeLine: true,
      subtitle: Text(post.body),
      dense: true,
    );
  }
}
